package com.zenith.article.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zenith.article.mapper.ArtArticleMapper;
import com.zenith.article.po.domain.ArtArticle;
import com.zenith.article.po.dto.ArtArticleDTO;
import com.zenith.article.service.ArtArticleService;
import com.zenith.common.result.PageResult;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

/**
 * 文章主表服务实现类
 *
 * @author zenith
 * @since 2025-08-29
 */
@Service
public class ArtArticleServiceImpl extends ServiceImpl<ArtArticleMapper, ArtArticle> implements ArtArticleService {

    @Override
    public PageResult<ArtArticle> getArtArticlePage(ArtArticleDTO query) {
        // 构造分页对象
        Page<ArtArticle> page = new Page<>(query.getPageNum(), query.getPageSize());
        
        // 构造查询条件
        LambdaQueryWrapper<ArtArticle> wrapper = new LambdaQueryWrapper<>();
        if (query.getTitle() != null && !query.getTitle().isEmpty()) {
            wrapper.like(ArtArticle::getTitle, query.getTitle());
        }
        if (query.getAuthorId() != null) {
            wrapper.eq(ArtArticle::getAuthorId, query.getAuthorId());
        }
        if (query.getCategoryId() != null) {
            wrapper.eq(ArtArticle::getCategoryId, query.getCategoryId());
        }
        if (query.getStatus() != null) {
            wrapper.eq(ArtArticle::getStatus, query.getStatus());
        }
        
        // 执行分页查询
        page = this.page(page, wrapper);
        
        // 返回分页结果
        return  PageResult.ofPage(page.getCurrent(), page.getSize(), page.getTotal(), page.getRecords());
    }

    @Override
    public boolean createArtArticle(ArtArticleDTO articleDTO) {
        ArtArticle article = new ArtArticle();
        BeanUtils.copyProperties(articleDTO, article);
        return this.save(article);
    }

    @Override
    public boolean updateArtArticle(ArtArticleDTO articleDTO) {
        ArtArticle article = new ArtArticle();
        BeanUtils.copyProperties(articleDTO, article);
        return this.updateById(article);
    }

    @Override
    public boolean deleteArtArticle(Long id) {
        return this.removeById(id);
    }

    @Override
    public boolean publishArtArticle(Long id) {
        ArtArticle article = new ArtArticle();
        article.setId(id);
        article.setStatus(1); // 1表示已发布
        return this.updateById(article);
    }

    @Override
    public ArtArticleDTO getArtArticleDetail(Long id) {
        ArtArticle article = this.getById(id);
        if (article == null) {
            return null;
        }
        ArtArticleDTO articleDTO = new ArtArticleDTO();
        BeanUtils.copyProperties(article, articleDTO);
        return articleDTO;
    }
}